`
# run some commands until the condition is no longer false
done
Listing 2-11
The until loop syntax
Listing 2-12 uses until to run some commands until a file’s size is greater
than zero (meaning it is not empty).
#!/bin/bash
FILE="output.txt"
touch "${FILE}"
until [[ -s "${FILE}" ]]; do
echo "$FILE is empty..."
echo "Checking again in 2 seconds..."
sleep 2
done
echo "${FILE} appears to have some content in it!"
Listing 2-12
An until loop to check a file’s size
We first create an empty file, then begin a loop that runs until the file is no
longer empty. Within the loop, we print some messages to the terminal. Save this
file as until_loop.sh and run it:
$ chmod u+x until_loop.sh
$ ./until_loop.sh
output.txt is empty...
Checking again in 2 seconds...
--snip--
At this point, the script has created the file output.txt, but it’s an empty file.
We can check this using the du command:
$ du -sb output.txt
output.txt
Open another terminal and navigate to the location at which your script is
saved, then append some content to the file so its size is no longer zero:
$ echo "until_loop_will_now_stop!" > output.txt
The script should exit the loop, and you should see it print the following:
output.txt appears to have some content in it!
This script is available at https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch02/until_loop.sh.
for
The for loop iterates over a sequence, such as a list of filenames, variables,
or even group of values generated by running some command. Inside the for
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks